import * as monaco from 'monaco-editor'
import { getSuggestionsTypeScript } from './components/typescript'

import type { BwMonacoEditorSnippetsModel, BwRangeModel } from '../model'

/** 创建代码片段 */
const createSnippets = (
  language: string,
  snippets?: Array<BwMonacoEditorSnippetsModel>
) => {
  language = language ?? 'typescript'

  monaco.languages.registerCompletionItemProvider(language, {
    provideCompletionItems: (model, position) => {
      const word = model.getWordUntilPosition(position)
      const range: BwRangeModel = {
        startLineNumber: position.lineNumber,
        endLineNumber: position.lineNumber,
        startColumn: word.startColumn,
        endColumn: word.endColumn,
      }

      let suggestions: monaco.languages.CompletionItem[] = []
      const predefine = getSuggestions(language, range)
      suggestions = suggestions.concat(predefine)

      if (snippets) {
        snippets.forEach((item) => {
          item.range = range
          suggestions.push(item)
        })
      }

      return {
        suggestions: suggestions,
      }
    },
  })
}

const getSuggestions = (language: string, range: BwRangeModel) => {
  let listSuggestions: Array<monaco.languages.CompletionItem> = []

  switch (language) {
    case 'typescript':
    case 'javascript':
      listSuggestions = getSuggestionsTypeScript(range)
      break

    case 'html':
    case 'handlebars':
    case 'razor':
      break

    case 'css':
    case 'scss':
    case 'less':
      break

    case 'json':
      break

    default:
      break
  }

  return listSuggestions
}

export { createSnippets }
